package com.cn.xiongmeng.czlxz.ui;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.cn.xiongmeng.czlxz.R;
import com.cn.xiongmeng.czlxz.activity.WorkActivity;
import com.cn.xiongmeng.czlxz.utils.GenerateWenzhang;

import java.util.ArrayList;

public class WenzhangFragment extends Fragment {
    private static final String TAG = "WenzhangFragment";
    WorkActivity activity;
    private GridLayout gridLayout;
    private String incorrectSentence; // 要填充的文字
    private String correctSentence;
    private String[] incorrectTextArray;
    private String[] correctTextArray;
    private ArrayList<Integer> indexOfFindedChars;
    private int totalIncorrectChar;
    private int imageView2Id;

    public WenzhangFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.d(TAG, "onAttach");
        // 获取Activity实例
        activity = (WorkActivity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_wenzhang, container, false);
        gridLayout = rootView.findViewById(R.id.gridLayout);

        init();
        return rootView;
    }


    public void init() {
        // Log.d(TAG, "init: ");
        // 获取GridLayout中的子视图数量
        int childCount = gridLayout.getChildCount();

        // Log.d(TAG, "init: 子视图数量为" + childCount);
        if (childCount>0){
            // 从后往前移除子视图，避免因索引变化导致的错误
            for (int i = childCount - 1; i >= 0; i--) {
                gridLayout.removeViewAt(i);
            }
        }

        imageView2Id = View.generateViewId();
        initWenzhang(); // 先初始化需要填充的文章

        int rowCount = 10;
        int columnCount = 10;
        gridLayout.setRowCount(rowCount);
        gridLayout.setColumnCount(columnCount);


        // 1、文章框框的构建
        for (int i = 0; i < rowCount; i++) {
            for (int j = 0; j < columnCount; j++) {
                FrameLayout frameLayout = new FrameLayout(requireContext());

                // 设置 FrameLayout 的布局参数
                GridLayout.LayoutParams params = new GridLayout.LayoutParams();
                params.width = 0; // 使用权重分配宽度
                params.height = 0; // 使用权重分配高度
                params.rowSpec = GridLayout.spec(i, 1, 1.0f); // 行权重
                params.columnSpec = GridLayout.spec(j, 1, 1.0f); // 列权重
                frameLayout.setLayoutParams(params);

                // 设置背景（如边框等）
                frameLayout.setBackgroundResource(R.drawable.square_border);

                // 将 FrameLayout 添加到 GridLayout
                gridLayout.addView(frameLayout);
            }
        }
        // 2、将文字填充到frameLayout，并加以监听
        for (int i = 0; i < incorrectTextArray.length; i++) {
            int posOfFrameLayout = i + 2; // 空两格 再填充文字
            // char character = incorrectSentence.charAt(i);
            String incorrectCharacter = incorrectTextArray[i];
            String correctCharacter = correctTextArray[i];

            // 创建 ImageView 可能展示背景
            ImageView imageView = new ImageView(requireContext());
            imageView.setLayoutParams(new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT));
            imageView.setImageResource(R.drawable.item_bg); // 设置图片资源
            imageView.setVisibility(View.GONE); // 默认不可见

            ImageView imageView2 = null;
            if (!(incorrectCharacter.equals(correctCharacter))) {
                // Log.d(TAG, "init: 不相等");
                // 创建 ImageView 点击提示，会展示
                imageView2 = new ImageView(requireContext());
                imageView2.setId(imageView2Id);
                imageView2.setLayoutParams(new FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.MATCH_PARENT,
                        FrameLayout.LayoutParams.MATCH_PARENT));
                imageView2.setImageResource(R.drawable.yuanquan); // 设置图片资源
                imageView2.setVisibility(View.GONE); // 默认不可见
            }

            // 创建 TextView 以显示字
            TextView textView = new TextView(requireContext());
            textView.setText(incorrectCharacter);
            textView.setTextSize(18); // 设置文字大小
            // textView.setTextColor(Color.parseColor("#FFFFFF"));
            textView.setGravity(Gravity.CENTER); // 居中显示


            View child = gridLayout.getChildAt(posOfFrameLayout); // 从gridLayout中按索引获取frameLayout
            // 将 TextView、ImageView 添加到 FrameLayout 中
            if (child instanceof FrameLayout) {
                FrameLayout frameLayout = (FrameLayout) child;

                frameLayout.addView(imageView);

                if (imageView2 != null) {
                    // Log.d(TAG, "init: 添加进入frameLayout");
                    frameLayout.addView(imageView2);
                }
                frameLayout.addView(textView);
                // Log.d(TAG, "FrameLayout at position " + posOfFrameLayout + " is: " + frameLayout);
            }


            // 设置点击事件（写好了，不用再看）
            ImageView finalImageView = imageView2;
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    activity.showInterstitialAdByProbability();

                    FrameLayout frameLayout = (FrameLayout) v.getParent();
                    int index = getPositionInGridLayout(frameLayout);
                    int posOfText = index - 2; // 这个字，在句子中的索引
                    String clickedChar = ((TextView) v).getText().toString();

                    String correctChar = correctTextArray[posOfText];

                    // if (clickedChar.equals(String.valueOf(correctChar))) {
                    if (clickedChar.equals(correctChar)) {
                        activity.deleteCurLifeValue();
                    } else {
                        // 判断 这个字的index是否在indexOfFindedChars
                        //  1、如果在，说明clickedChar是正确的字
                        //  2、如果不在，说明clickedChar是错的字

                        // (1)、交换
                        incorrectTextArray[posOfText] = correctChar;
                        correctTextArray[posOfText] = clickedChar;

                        if (indexOfFindedChars.contains(posOfText)) {
                            // (2)、删除
                            indexOfFindedChars.remove(Integer.valueOf(posOfText)); // 删除值为posOfText的元素
                            // (3)、setText、取消背景、选出的错字数减一
                            ((TextView) v).setText(correctChar);
                            imageView.setVisibility(View.GONE);
                            activity.deleteCurFindedIncorrectChar();
                        } else {
                            // (2)、添加
                            indexOfFindedChars.add(posOfText);
                            // (3)、setText、显示背景、选出的错字数加一
                            ((TextView) v).setText(correctChar);
                            imageView.setVisibility(View.VISIBLE);
                            if (finalImageView != null) {
                                finalImageView.setVisibility(View.INVISIBLE);
                            }
                            activity.addCurFindedIncorrectChar();

                            // Log.d("GridLayout", "选对了");
                        }
                    }
                }
            });
        }
    }

    private int getPositionInGridLayout(FrameLayout frameLayout) {
        // 从gridLayout中按frameLayout获取索引
        int index = gridLayout.indexOfChild(frameLayout);

        return index;
    }

    private void initWenzhang() {
        String[] ss = GenerateWenzhang.generateWenzhang();
        incorrectSentence = ss[0]; // 要填充的文字
        correctSentence = ss[1];
        incorrectTextArray = incorrectSentence.split(""); // 将文本拆分为字符数组
        correctTextArray = correctSentence.split(""); // 将文本拆分为字符数组
        indexOfFindedChars = new ArrayList<>();
        totalIncorrectChar = countDifferentCharacters(incorrectSentence, correctSentence); // 所有需要找出来的错字数目
        // indexOfFindedChars.add(1);
        // indexOfFindedChars.remove(0); // 删除索引为0的元素
        // indexOfFindedChars.remove(Integer.valueOf(2)); // 删除值为2的元素
        // int length = indexOfFindedChars.size(); // 输出数组长度
        // indexOfFindedChars.contains(element); // 判断元素是否在 数组中
    }

    private int countDifferentCharacters(String s1, String s2) {
        int count = 0;

        // 确保两个字符串长度相同，否则无法逐字符比较
        if (s1.length() != s2.length()) {
            throw new IllegalArgumentException("两个字符串的长度必须相同");
        }

        // 逐字符比较
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                count++;
            }
        }

        return count;
    }

    public int getTotalIncorrectChar() {
        return totalIncorrectChar;
    }

    public void onClickTishi() {
        for (int j = 0; j < incorrectTextArray.length; j++) {
            int i = j + 2;
            // 判断 这个字的index是否在indexOfFindedChars
            //  1、如果在，说明clickedChar是正确的字，不展示提示,因为，用户已经点出来了
            //  2、如果不在，说明clickedChar是错的字
            if (indexOfFindedChars.contains(j)) {
                continue;
            }
            View child = gridLayout.getChildAt(i);
            if (child instanceof FrameLayout) {
                // 获取FrameLayout
                FrameLayout frameLayout = (FrameLayout) child;
                // 获取ImageView实例
                ImageView imageView2 = frameLayout.findViewById(imageView2Id);
                if (imageView2 != null) {
                    imageView2.setVisibility(View.VISIBLE);
                }
            }
        }
    }
}